#include <kutils.h>
#include "sound.h"
#include "display.h"
#include "memory.h"

void beep_on(u32int hz);
void beep_off(void);

extern volatile u32int seconds;		//in the timer code

void beep_on(u32int hz)
{
	u32int divisor = 1193180 / hz;
	outportb(0x43, 0xb6);
	outportb(0x42, (u8int)(divisor));
	outportb(0x42, (u8int)(divisor >> 8));

	u8int in = inportb(0x61);
	in |= 0x03;
	outportb(0x61,in);//connect the speaker	
}

void beep_off(void)
{
	u8int in = inportb(0x61);
	in = (u8int)(in & 0xFC);
	outportb(0x61,in);//disconnect the speaker	
}

void beep(u32int hz, u32int num_beeps, u32int beep_ms, u32int delay_ms)
{
	u32int i = 0;
	for(i = 0; i < num_beeps; i++)
	{
		beep_on(hz);
		wait(beep_ms);
		beep_off();
		wait(delay_ms);
	}
}
/*
void play_audio_16bit(audio_16bit_t *a)
{
	disable_interrupts();
	u32int loop = 1;
	u32int i = 0;
	u32int b = 0;
	u8int sample;
	u32int pulse_count;
	u32int pulse_multiple;
	s8int out = (inportb(0x61) | 0x02);
	s8int in = (inportb(0x61) & 0xBF);

	while(loop)
	{
		for(i = 0; i < a->length; i++)
		{
			sample = (((a->data[i] * a->bbs) / a->sps) * 255) / 65535;
			pulse_count = (sample * a->bbs) / 100;
			pulse_multiple =(a->bbs / (pulse_count + 1)) + 1;		

			//write_number(sample);		

			for(b = 0; b < a->bbs; b++)
			{
				if(b % pulse_multiple)
				{
					outportb(0x61, out);
				}
				else
				{
					outportb(0x61, in);
				}
			}
		}
		loop--;
	}
	enable_interrupts();
}

void init_audio_16bit(audio_16bit_t *a)
{
	write_string("Sound: Initalizing audio object...");
	//find the number of bits that can be sent in the time between samples
	volatile u32int bps;						//bits per second
	s8int in = inportb(0x61);
	in &= 0xFD;

	//wait for the second to start
	volatile u32int tmp = seconds;//no funky optomizations please
	while(seconds == tmp)
	{}
	tmp = seconds;
	while(seconds == tmp)
	{
		//send out some bits to the pc speaker and count how many can be sent in one second
		outportb(0x61,in);//send the speaker zeros	
		bps++;
	}
	
	//the final calculation
	a->bbs = bps / a->sps;
	write_string(" bps: ");
	write_number(bps);
	write_string(" bbs: ");
	write_number(a->bbs);
}
*/
void init_sound(void)
{
#ifdef FLUIDIUM_DEBUG
	write_string("Sound: Init\n");
#endif
}

